<?php
/**
 * Created by PhpStorm.
 * User: 技术员专用
 * Date: 2019/3/12
 * Time: 14:30
 */
class Ws{
    const HOST='0.0.0.0';
    const PORT=8812;
    public $ws=null;
    public function __construct()
    {
        $this->ws = new Swoole\WebSocket\Server('0.0.0.0', 8812);
        $this->ws->set([
            'worker_num'=>2,
            'task_worker_num'=>2,
        ]);
        $this->ws->on('open',[$this,'onOpen']);
        $this->ws->on('message',[$this,'onMessage']);
        $this->ws->on('task',[$this,'onTask']);
        $this->ws->on('finish',[$this,'onFinish']);
        $this->ws->on('close',[$this,'onClose']);
        $this->ws->start();
    }

    /**
     * 监听ws链接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws,$request){
        var_dump($request->fd);
        swoole_timer_tick(2000,function ($timerId){
            echo "2s:$timerId".PHP_EOL;
        });
    }

    /**
     * 监听ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws,$frame){
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}".PHP_EOL;
        $data=[
            'task'=>1,
            'fd'=>$frame->fd,
        ];
//        $ws->task($data);
        swoole_timer_after(5000,function ()use($ws,$frame){
            echo '5s after'.PHP_EOL;
            $ws->push($frame->fd,'timer_after_server');
        });
        $ws->push($frame->fd, "this is server".date('Y-m-d H:i:s'));
    }

    public function onTask($serv,$taskId,$workId,$data){
        print_r($data);
        sleep(10);
        return 'on task finish';
    }
    public function onFinish($serv,$taskId,$data){
        echo "task-id:$taskId".PHP_EOL;
        echo "finish-data-success:$data".PHP_EOL;
    }
    /**
     * 监听ws关闭时间
     * @param $ws
     * @param $fd
     */
    public function onClose($ws,$fd){
        echo "client {$fd} closed".PHP_EOL;
    }
}
$obj=new Ws();